package online.flowerinsnow.rmrf;

import java.io.File;
import java.util.Arrays;

public class RmRf {
    private RmRf() {
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        if (args.length == 0) {
            System.out.println("[?]用法: rmrf <文件/文件夹路径>");
            System.out.println("[!]程序在 " + (int) (System.currentTimeMillis() - start) + "ms 完成");
            return;
        }

        StringBuilder var1 = new StringBuilder();
        for (int i = 0; i < args.length; i++) {
            var1.append(args[i]);
            if (i + 1 < args.length) var1.append(" ");
        }

        String path = var1.toString();

        System.out.println(":check ...");
        File file;
        try {
            file = check(path);
            if (file == null) {
                System.err.println(":check ×");
                System.err.println("[!]程序在 " + (int) (System.currentTimeMillis() - start) + "ms 失败");
                return;
            }
        } catch (Throwable ex) {
            ex.printStackTrace();
            System.err.println(":check ×");
            System.err.println("[!]程序在 " + (int) (System.currentTimeMillis() - start) + "ms 失败");
            return;
        }

        System.out.println(":check √");

        System.out.println(":delete ...");
        try {
            if (delete(file)) {
                System.out.println("[!]文件全部删除成功");
            } else {
                System.out.println("[!]文件删除部分失败");
            }
        } catch (Throwable ex) {
            System.err.println(":delete ×");
            ex.printStackTrace();
            System.err.println("[!]程序在 " + (int) (System.currentTimeMillis() - start) + "ms 失败");
            return;
        }

        System.out.println(":delete √");
        System.out.println("[!]程序在 " + (int) (System.currentTimeMillis() - start) + "ms 完成");
    }

    private static File check(String path) {
        File file = new File(path);
        if (file.exists()) {
            return file;
        } else {
            System.err.println("[×]文件或目录不存在");
            return null;
        }
    }

    private static boolean delete(File file) {
        if (file.isFile()) {
            if (!file.delete()) {
                System.out.println("[!]无法删除文件: " + file.getPath());
                return false;
            } else {
                return true;
            }
        } else if (file.isDirectory()) {
            boolean[] failed = {false};
            Arrays.stream(file.listFiles()).forEach(f -> {
                if (!delete(f)) failed[0] = true;
            });
            if (failed[0]) {
                return false;
            } else {
                file.delete();
                return true;
            }
        } else {
            return true;
        }
    }
}
